import { ref, computed } from 'vue'

export function useHistory(getCanvas) {
  const history = ref([])
  const currentStateIndex = ref(-1)
  const maxStates = 30 // 最大历史记录数

  // 可以撤销和重做的状态
  const canUndo = computed(() => currentStateIndex.value > 0)
  const canRedo = computed(() => currentStateIndex.value < history.value.length - 1)

  // 保存当前状态
  const saveState = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    // 获取当前画布状态
    const json = JSON.stringify(fabricCanvas.toJSON())

    // 如果是在历史记录中间的状态进行了修改，删除后面的记录
    if (currentStateIndex.value < history.value.length - 1) {
      history.value = history.value.slice(0, currentStateIndex.value + 1)
    }

    // 添加新状态
    history.value.push(json)
    
    // 如果超过最大记录数，删除最早的记录
    if (history.value.length > maxStates) {
      history.value.shift()
    }

    currentStateIndex.value = history.value.length - 1
  }

  // 初始化历史记录监听
  const initHistoryObserver = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    // 监听画布变化事件
    fabricCanvas.on('object:modified', saveState)
    fabricCanvas.on('object:added', saveState)
    fabricCanvas.on('object:removed', saveState)

    // 保存初始状态
    saveState()
  }

  // 撤销
  const undo = () => {
    if (!canUndo.value) return

    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    currentStateIndex.value--
    loadState(currentStateIndex.value)
  }

  // 重做
  const redo = () => {
    if (!canRedo.value) return

    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    currentStateIndex.value++
    loadState(currentStateIndex.value)
  }

  // 加载指定状态
  const loadState = (index) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const state = history.value[index]
    if (!state) return

    fabricCanvas.loadFromJSON(JSON.parse(state), () => {
      fabricCanvas.renderAll()
    })
  }

  // 清空历史记录
  const clearHistory = () => {
    history.value = []
    currentStateIndex.value = -1
    saveState() // 保存当前状态作为新的初始状态
  }

  return {
    history,
    currentStateIndex,
    canUndo,
    canRedo,
    initHistoryObserver,
    saveState,
    undo,
    redo,
    clearHistory
  }
} 